import React, { Component } from 'react'
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Table } from 'antd';

class PlaybackSelectPage extends Component {
  static propTypes = {
    // prop: PropTypes
  }

  state = {
    cook_times: [],
  }

  componentDidMount() {
    const { match, dispatch } = this.props;
    const { params } = match;
    const { method } = params;

    dispatch({
      type: 'playback/fetchModelList',
    });

    if(method){
      this.handleModelClick(method);
    }
  }

  handleModelClick = (model) => {
    const { dispatch } = this.props;
    console.log(model);
    dispatch({
      type: 'playback/save',
      payload: {
        key: 'selectModel',
        value: model,
      }
    });

    dispatch({
      type: 'playback/fetchCookList',
      payload: {
        model,
      }
    });
  }

  handleCookClick = (time) => {
    const { dispatch, playback } = this.props;
    const { selectModel } = playback;
    dispatch(routerRedux.push(`/result/${selectModel}/${time}`));
  }

  render() {
    const { models, cook_times } = this.props.playback;

    const columns = [
      {
        title: '烹饪时间',
        dataIndex: 'cook_time',
        key: 'cook_time',
        render: time => <a href='javascript:;' onClick={() => this.handleCookClick(time)}>{time}</a>,
        sorter: (a, b) => {
          let splitA = a.cook_time.split('_');
          let splitB = b.cook_time.split('_');
          let result = 0;
          for(let i=0;i<splitA.length;i++){
            const intA = parseInt(splitA[i]);
            const intB = parseInt(splitB[i]);
            result = intA - intB;
            if(result !== 0){
              return result;
            }
          }
          return result;
        },
        defaultSortOrder: 'descend',
      },
    ];

    return (
      <div>
        <div>
          <h2>method + model</h2>
          <ul>
            {
              models.map(model => {
                return (
                  <li key={model}>
                    <a href='javascript:;' onClick={() => this.handleModelClick(model)}>{model}</a>
                  </li>
                );
              })
            }
          </ul>
        </div>
        <div>
          <h2>cook time</h2>
          <Table dataSource={cook_times} columns={columns} pagination={false} rowKey={record => record.cook_time}/>
        </div>
      </div>
    )
  }
}

export default connect(({playback}) => {
  return {playback};
})(PlaybackSelectPage);
